<template>
  <div class="chart-view-container">
    <a-empty v-if="empty"></a-empty>
    <div class="chart-dom" ref="chart-dom" v-else></div>
  </div>
</template>

<script>
import { deepMerge } from "@/utils";
import charMixins from "@/mixins/echarts";
export default {
  name: "ChartView",
  props: {
    //echart配置
    options: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  watch: {
    options: {
      handler(val) {
        this.initLineChar();
      },
      deep: true,
    },
  },
  data() {
    return {
      empty: false,
    };
  },
  mounted() {
    this.initLineChar();
  },
  mixins: [charMixins],
  methods: {
    //初始化图标
    initLineChar() {
      this.checkOptionIsValid();
      this.$nextTick((_) => {
        setTimeout((_) => {
          !this.empty && this.drawChar();
        }, 300);
      });
    },

    //绘制图标
    drawChar() {
      let chart_dom = this.$refs["chart-dom"];
      this.chartInstance && this.chartInstance.dispose();
      this.chartInstance = this.$echarts.init(chart_dom);
      let baseOpt = {
        grid: {
          top: 100,
          left: 50,
          right: 50,
        },
      };
      this.chartInstance.setOption(
        deepMerge(this.lineChartsOptions, baseOpt, this.options)
      );
      //开启响应式
      window.addEventListener("resize", () => {
        this.chartInstance.resize();
      });
      //渲染结束事件。注意 rendered 事件并不代表渲染动画
      this.chartInstance.on("rendered", () => {
        this.$emit("rendered", this.chartInstance);
      });

      //渲染完成事件，并且动画也渲染结束
      this.chartInstance.on("finished", () => {
        this.$emit("finished", this.chartInstance);
      });
    },

    //判断当前的图表数据是否有效
    checkOptionIsValid() {
      if (Object.prototype.toString.call(this.options) != "[object Object]") {
        this.empty = true;
      } else {
        let { xAxis, series } = this.options;
        if (
          !xAxis ||
          (xAxis &&
            !Array.isArray(xAxis) &&
            (!xAxis.data || !Array.isArray(xAxis.data))) ||
          !this.checkSeries(series)
        ) {
          this.$emit("rendered", null);
          this.empty = true;
        } else {
          this.empty = false;
        }
      }
    },

    //校验series
    checkSeries(series) {
      if (!series) {
        return false;
      } else if (Object.prototype.toString.call(series) == "[object Object]") {
        return series.data && series.data.length > 0;
      } else if (Array.isArray(series)) {
        return series.every((v) => v.data && v.data.length > 0);
      } else {
        return false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.chart-view-container {
  width: 100%;
  height: 100%;
  .chart-dom {
    height: 100%;
    width: 100%;
  }
}
</style>
